package com.han.yrpc.registrycenter.localcache;

import com.han.yrpc.core.provider.AbstractServiceRegistry;
import com.han.yrpc.core.provider.ServiceCache;
import com.han.yrpc.core.registry.Register;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

@Slf4j
@Component
public class SimpleServiceRegistry extends AbstractServiceRegistry {

    private final Register register;

    protected SimpleServiceRegistry(ServiceCache serviceCache, Register register) {
        super(serviceCache);
        this.register = register;
    }

    @Override
    public void doRegistry(String serviceName, Class<?> clazzImpl) {
        try {
            String host = InetAddress.getLocalHost().getHostAddress();
            this.doRegistry(serviceName, host, 8888);
        } catch (UnknownHostException ignored) {
        }
    }

    public void doRegistry(String serviceName, String host, int port) {
        Socket socket = new Socket();
        try {
            socket.connect(register.getInetSocketAddress());
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());) {
            outputStream.writeBoolean(true);
            outputStream.writeUTF(serviceName);
            outputStream.writeUTF(host);
            outputStream.writeInt(port);
            outputStream.flush();

            boolean success = inputStream.readBoolean();
            if (success) {
                log.info("[{}] register success", serviceName);
            }

        } catch (IOException e) {
            log.error("occur IOException: {}", e.getMessage());
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
